package com.zyp.shop.interceptor;

import com.alibaba.fastjson2.JSONObject;

import com.zyp.shop.util.JwtUtil;
import com.zyp.shop.vo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by Intellij IDEA
 * 登录拦截器
 * @author 赵雅璞
 * @Date: 2022/11/23 15:22
 * @Version 1.0
 */

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        //1.获取请求头种的token
        String token = request.getHeader("token");
        System.out.println("++++"+token);
        //2.判断token是否为null
        if (StringUtils.hasText(token)){
            //校验token是否合法
            if (JwtUtil.verifyToken(token)) return true;
        }
        PrintWriter writer = response.getWriter();
        writer.print(JSONObject.toJSONString(new Result(4001,"未登录")));
        writer.flush();
        writer.close();
        return false;
    }
}
